from functools import wraps
from flask import request, jsonify
from flask_jwt_extended import get_jwt_identity, verify_jwt_in_request
from app.models import Admin
from app.utils.response import error_response

def admin_required(fn):
    """管理员权限验证装饰器"""
    @wraps(fn)
    def wrapper(*args, **kwargs):
        try:
            verify_jwt_in_request()
            current_user_id = get_jwt_identity()
            
            # 检查是否为管理员
            if not str(current_user_id).startswith('admin_'):
                return error_response('需要管理员权限', 403)
            
            admin_id = int(current_user_id.split('_')[1])
            admin = Admin.query.get(admin_id)
            
            if not admin or not admin.is_active:
                return error_response('管理员账户无效', 403)
            
            return fn(*args, **kwargs)
            
        except Exception as e:
            return error_response('权限验证失败', 401)
    
    return wrapper

def super_admin_required(fn):
    """超级管理员权限验证装饰器"""
    @wraps(fn)
    def wrapper(*args, **kwargs):
            
        try:
            verify_jwt_in_request()
            current_user_id = get_jwt_identity()
            
            # 检查是否为管理员
            if not str(current_user_id).startswith('admin_'):
                return error_response('需要管理员权限', 403)
            
            admin_id = int(current_user_id.split('_')[1])
            admin = Admin.query.get(admin_id)
            
            if not admin or not admin.is_active:
                return error_response('管理员账户无效', 403)
            
            if not admin.is_super_admin:
                return error_response('需要超级管理员权限', 403)
            
            return fn(*args, **kwargs)
            
        except Exception as e:
            return error_response('权限验证失败', 401)
    
    return wrapper

def user_required(fn):
    """用户权限验证装饰器"""
    @wraps(fn)
    def wrapper(*args, **kwargs):
        # 处理OPTIONS请求
        if request.method == 'OPTIONS':
            return jsonify({}), 200
            
        try:
            verify_jwt_in_request()
            current_user_id = get_jwt_identity()
            
            # 检查是否为普通用户
            if str(current_user_id).startswith('admin_'):
                return error_response('需要用户权限', 403)
            
            return fn(*args, **kwargs)
            
        except Exception as e:
            return error_response('权限验证失败', 401)
    
    return wrapper 